package org.example.helloworld.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {
    @PostMapping("/upload")
    public String up(String nickname, MultipartFile photo, HttpServletRequest request)  throws IOException {
        System.out.println(nickname);
//        获取上传的文件名
        System.out.println(photo.getOriginalFilename());
//        获取上传的文件类型
        System.out.println(photo.getContentType());
        System.out.println(System.getProperty("user.dir"));

//        获取当前的项目路径
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        saveFile(photo, path);
        return "文件上传成功";
    }

    private void saveFile(MultipartFile photo, String path) throws IOException {
//        不存在则，创建上传的文件夹
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
//        保存上传的文件
        File newFile = new File(path+photo.getOriginalFilename());
        photo.transferTo(newFile);
    }
}
